package cn.ganzhiqiang.ares.context;

import com.duitang.boot.actuatemysql.DataSourceConfig;
import com.duitang.boot.actuatemysql.MySQLClientHelper;

import com.zaxxer.hikari.HikariDataSource;

import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author nanxuan
 * @since 2017/12/10
 **/

@Configuration
public class MysqlConfig {
  @Value("${mysql.ayy.url}")
  private String ayyUrl;
  @Value("${mysql.ayy.user}")
  private String ayyUsername;
  @Value("${mysql.ayy.password}")
  private String ayyPassword;

  @Bean
  public HikariDataSource ayyMaster() {
    return MySQLClientHelper.createDataSource(createDataSourceConfig(),
        ayyUrl, ayyUsername, ayyPassword);
  }

  private DataSourceConfig createDataSourceConfig() {
    DataSourceConfig dataSourceConfig = new DataSourceConfig();
    dataSourceConfig.setMaxActive(60);
    dataSourceConfig.setMaxIdle(60);
    dataSourceConfig.setMinIdle(60);
    dataSourceConfig.setInitialSize(2);
    dataSourceConfig.setMaxWait(3000);
    return dataSourceConfig;
  }

  @Bean(name = {"writeTpl", "readTpl"})
  public SqlSessionTemplate sqlSessionTemplate() throws Exception {
    return MySQLClientHelper.createSqlSessionTemplate(ayyMaster(), "cn.ganzhiqiang.ares",
        "classpath:cn/ganzhiqiang/ares/mapper/*.xml");
  }

  @Bean
  public TransactionTemplate transactionTpl() {
    return MySQLClientHelper.createTransactionTemplate(ayyMaster());
  }

}
